package com.handong.handserialprogram.module.singleperson;

import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.handong.handserialprogram.R;
import com.handong.handserialprogram.model.entities.FootRingNewEntity;
import com.handong.handserialprogram.model.status.EmergencyMsg;
import com.handong.handserialprogram.model.status.EmergencyResponse;
import com.handong.handserialprogram.model.status.FootRingStatus;
import com.handong.handserialprogram.model.status.RingResponse;
import com.handong.handserialprogram.module.base.BasePresenter;
import com.handong.handserialprogram.module.base.BaseView;
import com.handong.handserialprogram.module.serialport.SerialPortUtil;
import com.handong.handserialprogram.utils.AppUtil;
import com.handong.handserialprogram.utils.EventBusUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Vector;
import java.util.concurrent.CopyOnWriteArrayList;


/**
 * Created by Administrator on 2016/12/14.
 */

public class SinglePersonPresenter extends BasePresenter<SinglePersonActivity> implements SinglePersonContract.Presenter {

    private static final String TAG = SinglePersonPresenter.class.getSimpleName();

    private SerialPortUtil mSerialPortUtil;
    private FootRingNewEntity mRingEntity;
    private String FootRingId;

    public void setFootRingId(String footRingId) {
        FootRingId = footRingId;
    }
    public SinglePersonPresenter(BaseView view) {
        super(view);
        EventBusUtil.register(this);
        mSerialPortUtil = SerialPortUtil.getInstance(mView);

    }

    /**
     * 更新脚环状态信息
     */
    @Subscribe(priority = 95, threadMode = ThreadMode.MAIN)
    public void receiveFootRing(CopyOnWriteArrayList<FootRingNewEntity> list) {
//        if (mView == null || !mView.isResume()) {
//            return;
//        }
        if (mView == null ) {
            return;
        }
        if (mRingEntity == null) {
            for (FootRingNewEntity entity:list) {
                if(entity.getRingID().equals(FootRingId)){
                    mRingEntity =entity;
                }
            }
        }
        if (this.mView != null) {
            mView.updateDistanceInfo(mRingEntity);
        }
    }

    /**
     * 接收脚环处理返回
     */
    @Subscribe(priority = 95, threadMode = ThreadMode.MAIN)
    public void receiveRingResponse(RingResponse response) {
        switch (response.getResponseCode()) {
            case RingResponse.UPDATE_DISTANCE_ORDER://修改距离
                mView.dismissLoadingDialog();
                if (response.isSuccess()) {
                    AppUtil.showShortToast((Context) this.mView, "修改距离成功");
                    return;
                }
                AppUtil.showShortToast((Context) this.mView, "修改距离失败");
                break;

            case RingResponse.SIM_ERROR://sim错误
                mView.finish();
                break;

            case RingResponse.CLOSE_ALARM_RESPONSE://关闭警报
                mView.dismissLoadingDialog();
                if (response.isSuccess()) {
                    AppUtil.showShortToast(mView, "消除警报成功");
                } else {
                    AppUtil.showShortToast(mView, "消除警报失败");
                }
                break;

            default:
                return;
        }
    }

    /**
     * 接收紧急报警返回
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveEmergencyResult(EmergencyResponse response) {
        if (mView == null || !mView.isResume()){
            return;
        }
        mView.dealEmergencyResponse(response);
    }
    /**
     * 接收紧急情况返回
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveEmergencyMsg(EmergencyMsg msg) {
        if (mView == null || !mView.isResume()){
            return;
        }
        if (msg.isStart()) {
            mView.sendEmergencyRequest();
        } else {
            mView.askUserForEmergency();
        }
    }

    /**
     * 修改授权状态
     */
    public boolean setEmpowerStatus(boolean paramBoolean)
    {
        if (mRingEntity!=null)
        {
            mRingEntity.setEmpower(paramBoolean);
            return true;
        }
        else{
            return false;
        }
    }

    /**
     * 修改临时撤防状态
     */
    public boolean setWithdrawStatus(boolean paramBoolean)
    {
        if (mRingEntity!=null)
        {
            mRingEntity.setWithdraw(paramBoolean);
            return true;
        }
        else{
            return false;
        }
    }


    /**
     * 是否开启报警提示。
     */
    public void setRemindSound(boolean paramBoolean) {
        this.mSerialPortUtil.setPlaySound(paramBoolean);
    }
    /**
     * 设置距离
     */
    @Override
    public void updateRingSetDistance(String id, String newSetDistance) {
        this.mSerialPortUtil.updateDistance(id, newSetDistance);
    }

    /**
     * 关闭警报
     */
    public void closeRingEmergency(final String id) {
        MaterialDialog dialog = null;
//        if (mRingEntity == null || (mRingEntity.getStatus() == FootRingStatus.NORMAL
//                && mRingEntity.getSetRingDistance() > mRingEntity.getActualRingDistance()
//                && mRingEntity.getRingPower() >= 67)) {
//            dialog = new MaterialDialog.Builder(mView)
//                    .content("脚环并未报警，无需进行消警！")
//                    .positiveColorRes(R.color.back_ground_green)
//                    .positiveText(R.string.dialog_positive_text)
//                    .build();
//            dialog.show();
//            return;
//        }
        if(mRingEntity==null)
        {
            return;
        }
        if (mRingEntity.getStatus() == FootRingStatus.ESCAPE) {
//            dialog = new MaterialDialog.Builder(mView)
//                    .content("犯人已脱离管控，无法对其进行消警，请联系指挥中心进行操作！")
//                    .positiveColorRes(R.color.back_ground_green)
//                    .positiveText(R.string.dialog_positive_text)
//                    .build();
//            dialog.show();
            return;
        }
//        LinearLayout contentView = (LinearLayout) LayoutInflater.from(mView.getApplicationContext())
//                .inflate(R.layout.dialog_close_ring_voice, null);
//        TextView tip = (TextView) contentView.getChildAt(0);
//        dialog = new MaterialDialog.Builder(mView)
//                .title("脚环语音报警")
//                .customView(contentView, true)
//                .positiveColorRes(R.color.back_ground_green)
//                .negativeColorRes(R.color.bg_gray)
//                .negativeText(R.string.dialog_negative_text)
//                .positiveText(R.string.dialog_positive_text)
//                .onPositive(new MaterialDialog.SingleButtonCallback() {
//                    @Override
//                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                        mView.showLoadDialog("正在关闭脚环语音报警...");
//                        mSerialPortUtil.closeFootRingAlarm(id);
//                    }
//                })
//                .build();
//        dialog.show();
        //mView.showLoadDialog("正在关闭脚环语音报警...");
        mSerialPortUtil.closeFootRingAlarm(id);
        //AppUtil.showShortToast(mView, "关闭脚环语音报警成功");

    }

    /**
     * 设置脚环是否停止锁扣报警
     * @param id 脚环id
     * @param isStopAlarm 是否停止脚环锁扣报警
     */
    public void setLockIsStopAlarm(final String id,boolean isStopAlarm){
        mSerialPortUtil.setLockIsStopAlarm(id,isStopAlarm);
    }

    /**
            * 关闭警报
     */
    public void openRingEmergency(final String id) {
        MaterialDialog dialog = null;
//        if (mRingEntity == null || (mRingEntity.getStatus() == FootRingStatus.NORMAL
//                && mRingEntity.getSetRingDistance() > mRingEntity.getActualRingDistance()
//                && mRingEntity.getRingPower() >= 67)) {
//            dialog = new MaterialDialog.Builder(mView)
//                    .content("脚环并未报警，无需进行消警！")
//                    .positiveColorRes(R.color.back_ground_green)
//                    .positiveText(R.string.dialog_positive_text)
//                    .build();
//            dialog.show();
//            return;
//        }
        if(mRingEntity==null)
        {
            return;
        }
        if (mRingEntity.getStatus() == FootRingStatus.ESCAPE) {
//            dialog = new MaterialDialog.Builder(mView)
//                    .content("犯人已脱离管控，无法对其进行开启报警，请联系指挥中心进行操作！")
//                    .positiveColorRes(R.color.back_ground_green)
//                    .positiveText(R.string.dialog_positive_text)
//                    .build();
//            dialog.show();
            return;
        }
//        LinearLayout contentView = (LinearLayout) LayoutInflater.from(mView.getApplicationContext())
//                .inflate(R.layout.dialog_close_ring_voice, null);
//        TextView tip = (TextView) contentView.getChildAt(0);
//        dialog = new MaterialDialog.Builder(mView)
//                .title("脚环语音报警")
//                .customView(contentView, true)
//                .positiveColorRes(R.color.back_ground_green)
//                .negativeColorRes(R.color.bg_gray)
//                .negativeText(R.string.dialog_negative_text)
//                .positiveText(R.string.dialog_positive_text)
//                .onPositive(new MaterialDialog.SingleButtonCallback() {
//                    @Override
//                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                        mView.showLoadDialog("正在开启脚环语音报警...");
//                        mSerialPortUtil.openFootRingAlarm(id);
//                    }
//                })
//                .build();
//        dialog.show();
        //mView.showLoadDialog("正在开启脚环语音报警...");
        mSerialPortUtil.openFootRingAlarm(id);
        AppUtil.showShortToast(mView, "开启脚环语音报警成功");
    }




    public boolean isEscape() {
        return null == mRingEntity ? true : mRingEntity.getStatus() == FootRingStatus.ESCAPE;
    }

    @Override
    protected void exit() {
        EventBusUtil.unRegister(this);
        super.exit();
    }
}
